package com.harvest.scientific.ladder.page

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.harvest.scientific.ladder.base.BaActivity
import com.harvest.scientific.ladder.databinding.ActInfoCardBinding
import com.harvest.scientific.ladder.page.camerax.CameraxController
import com.harvest.scientific.ladder.util.ImageUtils
import com.harvest.scientific.ladder.util.LogUtils
import com.harvest.scientific.ladder.util.StbarUtil
import com.harvest.scientific.ladder.util.compress.ImageCompress
import com.harvest.scientific.ladder.util.compress.OnCompressListener
import java.io.File
import java.io.IOException
import java.util.Locale


class InfoCardActivity: BaActivity(), View.OnClickListener{

    private lateinit var binding: ActInfoCardBinding

    private val cameraxController: CameraxController = CameraxController()

    private lateinit var pictureOutputPath: String

    private val TAG = "InfoCardActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StbarUtil.setStatusBar(this,false, Color.TRANSPARENT,true)
        binding = ActInfoCardBinding.inflate(layoutInflater)
        setContentView(binding.root)
        pictureOutputPath = applicationContext.cacheDir.absolutePath+"${System.currentTimeMillis()}.png"
        initEvent()
        initCameraX()
    }

    private fun initEvent() {
        binding.llBack.setOnClickListener(this)
        binding.ivTake.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when(v) {
            binding.llBack -> {
                onBackPressed()
            }
            binding.ivTake -> {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                    if (checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        startTakePicture()
                    } else {
                        ActivityCompat.requestPermissions(this@InfoCardActivity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 100)
                    }
                } else {
                    startTakePicture()
                }
            }
        }
    }

    private fun initCameraX() {
        runCatching {
            cameraxController.initCameraX(this@InfoCardActivity, binding.previewView)
        }
    }


    private fun startTakePicture() {
        cameraxController.takePicture(pictureOutputPath, imageCaptureListener)
    }

    private val imageCaptureListener = object : ImageCapture.OnImageSavedCallback {
        override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
            runCatching {
                LogUtils.d(TAG,"imageCaptureListener path:${pictureOutputPath}")
                val savedUri = outputFileResults.savedUri ?: Uri.fromFile(File(pictureOutputPath))
                setResult(RESULT_OK, Intent().apply { this.putExtra("path", savedUri.path) })
                finish()
            }
        }

        override fun onError(exception: ImageCaptureException) {
            Log.d(TAG, "startTakePicture onError ${exception.stackTraceToString()}")
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == 100) {
                startTakePicture()
            }
        }
    }

    private fun checkPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(
            this@InfoCardActivity,
            permission
        ) == PackageManager.PERMISSION_GRANTED
    }

}